<template>
  <div>
    <v-container fluid grid-list-lg>
      <v-layout row wrap>
        <v-flex lg12 sm12 xs12>
          <v-layout row wrap>
            <v-flex lg3 sm6 xs12>
              <mini-statistic icon="fa fa-facebook" :title="chartData.total.storeMonetary" sub-title="消费总额" :left-title="chartData.total.storeTotal" left-sub-title="实收总额" color="purple"></mini-statistic>
            </v-flex>
            <v-flex lg3 sm6 xs12>
              <mini-statistic icon="fa fa-facebook" :title="chartData.total.ownerMonetary" sub-title="卡主消费" :left-title="chartData.total.ownerTotal" left-sub-title="实收金额" color="indigo"></mini-statistic>
            </v-flex>
            <v-flex lg3 sm6 xs12>
              <mini-statistic icon="fa fa-google" :title="chartData.total.familyMonetary" sub-title="亲情消费" :left-title="chartData.total.familyTotal" left-sub-title="实收金额" color="red"> </mini-statistic>
            </v-flex>
            <v-flex lg3 sm6 xs12>
              <mini-statistic icon="fa fa-facebook" :title="chartData.total.shareMonetary" sub-title="共享消费" :left-title="chartData.total.shareTotal" left-sub-title="实收金额" color="light-blue"></mini-statistic>
            </v-flex>
          </v-layout>
        </v-flex>
        <v-flex lg12 sm12 xs12>
          <v-card>
            <v-toolbar color="transparent" flat dense card>
              <v-toolbar-title>近15日营收概况</v-toolbar-title>
              <v-spacer></v-spacer>
              <v-toolbar-items class="hidden-sm-and-down">
                <v-btn icon slot="widget-header-action" @click="refreshChartData">
                  <v-icon class="text--secondary">refresh</v-icon>
                </v-btn>
              </v-toolbar-items>
            </v-toolbar>
            <v-flex lg12 sm12 xs12>
              <v-chart :options="polar" :auto-resize="true" ref="lineChart" />
            </v-flex>
          </v-card>
        </v-flex>

        <v-flex lg12 sm12 xs12>
          <v-card>
            <v-toolbar card :flat="true">
              <v-flex :style="{minWidth:'165px',maxWidth:'165px'}">
                <v-menu ref="startDate" lazy :close-on-content-click="false" v-model="startDateMenu" transition="scale-transition" offset-y full-width :nudge-bottom="-22" max-width="290px" :return-value.sync="startDate">
                  <v-text-field slot="activator" placeholder="开始日期" clearable v-model="startDate" prepend-icon="event" readonly></v-text-field>
                  <v-date-picker v-model="startDate" locale="zh-cn" no-title scrollable @input="$refs.startDate.save(startDate);startDateMenu = false">
                  </v-date-picker>
                </v-menu>
              </v-flex>
              <v-flex :style="{minWidth:'165px',maxWidth:'165px'}">
                <v-menu ref="endDate" lazy :close-on-content-click="false" v-model="endDateMenu" transition="scale-transition" offset-y full-width :nudge-bottom="-22" min-width="290px" :return-value.sync="endDate">
                  <v-text-field slot="activator" placeholder="结束日期" clearable v-model="endDate" prepend-icon="event" readonly></v-text-field>
                  <v-date-picker v-model="endDate" locale="zh-cn" no-title scrollable @input="$refs.endDate.save(endDate);endDateMenu = false"></v-date-picker>
                </v-menu>
              </v-flex>
              <v-flex :style="{minWidth:'285px'}">
                <v-tooltip bottom>
                  <v-btn fab slot="activator" icon @click="searchDateBetween">
                    <v-icon class="text--secondary">search</v-icon>
                  </v-btn>
                  <span>搜索</span>
                </v-tooltip>
                <v-tooltip bottom>
                  <v-btn fab slot="activator" icon>
                    <v-icon class="text--secondary">get_app</v-icon>
                  </v-btn>
                  <span>下载</span>
                </v-tooltip>
                <v-tooltip bottom v-if="desserts.length > 0">
                  <v-btn  fab slot="activator" icon @click="switchover">
                      <v-icon>swap_horiz</v-icon>
                  </v-btn>
                  <span>切换</span>
                </v-tooltip>
              </v-flex>
              <v-flex :style="{minWidth:'240px',maxWidth:'240px'}">
                <v-text-field placeholder="输入消费者姓名、卡主手机号" v-model="search"></v-text-field>
              </v-flex>
              <v-flex :style="{minWidth:'170px',maxWidth:'170px'}"> 
                <v-tooltip bottom>
                <v-btn fab slot="activator" icon @click="searchByNameOrMobile">
                  <v-icon class="text--secondary">search</v-icon>
                </v-btn>
                <span>搜索</span>
                </v-tooltip>
                <v-tooltip bottom>
                <v-btn fab slot="activator" icon @click="refreshTableData" >
                  <v-icon class="text--secondary">refresh</v-icon>
                </v-btn>
                <span>刷新</span>
                </v-tooltip>
              </v-flex>
            </v-toolbar>
            <v-divider></v-divider>
            <v-card-text class="pa-0 backdrop"  @click.native="jump">
              <v-data-table  v-if="tableOrTimeline" :headers="headers" :items="desserts" :rows-per-page-items="[10,20,50,{ text:'全部',value:totalDesserts}]" :pagination.sync="pagination" :total-items="totalDesserts" :loading="loading" class="elevation-1">
                <template slot="items" slot-scope="props">
                  <td class="text-xs-center">{{ (props.index+1)+((pagination.page-1)*pagination.rowsPerPage)}}</td>
                  <td class="text-xs-center">{{ props.item.orderNumber }}</td>
                  <td class="text-xs-center">{{ props.item.tradeAt }}</td>
                  <td class="text-xs-center">{{ props.item.customerName }}</td>
                  <td class="text-xs-right">{{ (props.item.monetary/100)|showMoneyFilter }}</td>
                  <td class="text-xs-center">{{ props.item.cardOwnerMobile }}/{{ props.item.memberShipCardInfo }}</td>
                  <td class="text-xs-right">{{ (props.item.deductionValue/100)|showMoneyFilter }}/{{ (props.item.balanceValue/100)|showMoneyFilter }}</td>
                </template>
              </v-data-table>
              <Timer-shaft  :items = "desserts" v-else></Timer-shaft>
            </v-card-text>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </div>
</template>
<script>
import MiniStatistic from "@/components/widgets/MiniStatistic";
import TimerShaft from "../components/TimerShaft.vue"
const SEARCH_TYPE_DEFALUT = 0; //默认加载关页面，搜索全部
const SEARCH_TYPE_NAME_OR_MOBLIE = 1; // 根据名称或者手机号搜索全部
const SEARCH_TYPE_DATE = 2; //根据日期范围搜索

export default {
  components: {
    MiniStatistic,
    TimerShaft
  },
  name: "StoreVoucher",
  data() {
    return {
      chartData: {
        total: {
          familyMonetary: 0,
          familyTotal: 0,
          ownerMonetary: 0,
          ownerTotal: 0,
          shareMonetary: 0,
          shareTotal: 0,
          storeMonetary: 0,
          storeTotal: 0
        },
        store15Day: []
      },

      totalDesserts: 0,
      desserts: [],
      loading: true,
      pagination: {
        sortBy: "tradeAt",
        descending: true
      },
      headers: [
        {
          text: "序号",
          value: "seq",
          sortable: false,
          align: "center",
          width: "10px"
        },
        {
          text: "订单编号",
          value: "name",
          sortable: false,
          align: "center",
          width: "150px"
        },
        {
          text: "时间",
          value: "tradeAt",
          align: "center",
          width: "167px"
        },
        {
          text: "消费者",
          value: "消费者",
          sortable: false,
          align: "center",
          width: "120px"
        },
        {
          text: "金额(元)",
          value: "金额",
          sortable: false,
          align: "center",
          width: "120px"
        },
        {
          text: "会员卡",
          value: "会员卡",
          sortable: false,
          align: "center",
          width: "300px"
        },
        {
          text: "卡扣减/余额(元)",
          value: "卡扣减/余额(元)",
          align: "center",
          sortable: false,
          width: "120px"
        }
      ],
      loading: true,
      polar: {},
      startDate: null,
      endDate: null,
      endDateMenu: false,
      startDateMenu: false,
      search: null,
      searchType: SEARCH_TYPE_DEFALUT,
      tableOrTimeline:true
    };
  },
  watch: {
    pagination: {
      handler() {
        if (this.pagination.sortBy == null) {
          return;
        }
        this.loading = true;
        this.getDataFromApi()
          .then(data => {
            this.desserts = data.items;
            this.totalDesserts = data.total;
            this.loading = false;
          })
          .catch(err => {
            this.loading = false;
          });
      },
      deep: true
    }
  },
  methods: {
    getDataFromApi() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        let items = [];
        let total = 0;
        this.getOrders().then(res => {
          items = res.content;
          total = res.totalElements;
          this.loading = false;
          resolve({
            items,
            total
          });
        });
      });
    },
    //获取订单数据
    getOrders() {
      return new Promise((resolve, reject) => {
        this.$ajax
          .get("/api/app/api/collection/voucher/store/all", {
            params: {
              storeId: 908,
              storeType: 1,
              pageNumber: this.pagination.page,
              size: this.pagination.rowsPerPage,
              sortBy: this.pagination.sortBy,
              descending: this.pagination.descending,
              searchKeywords: this.search,
              searchType: this.searchType,
              startDate: this.startDate,
              endDate: this.endDate
            }
          })
          .then(res => {
            resolve(res.data);
          })
          .catch(error => {
            console.error(error);
          });
      });
    },
    //获取概况数据
    getChartData() {
      return new Promise((resolve, reject) => {
        this.$ajax
          .get("/api/app/api/collection/voucher/store/chart/data", {
            params: {
              storeId: 908,
              storeType: 1
            }
          })
          .then(res => {
            resolve(res.data);
          })
          .catch(err => {
            console.error(err);
          });
      });
    },
    //根据日期搜索
    searchDateBetween() {
      if (this.startDate == null && this.endDate == null) {
        return;
      }
      this.searchType = SEARCH_TYPE_DATE;
      this.loading = true;
      if (this.pagination.page === 1) {
        this.getDataFromApi().then(data => {
          this.desserts = data.items;
          this.totalDesserts = data.total;
          this.loading = false;
        });
      } else {
        this.pagination.page = 1;
      }
    },
    //搜索 根据名称或者手机号
    searchByNameOrMobile() {
      if (this.search == null || this.search.length < 1) {
        return;
      }
      this.searchType = SEARCH_TYPE_NAME_OR_MOBLIE;
      this.loading = true;
      if (this.pagination.page === 1) {
        this.getDataFromApi().then(data => {
          this.desserts = data.items;
          this.totalDesserts = data.total;
          this.loading = false;
        });
      } else {
        this.pagination.page = 1;
      }
    },
    //刷新表格数据
    refreshTableData() {
      this.loading = true;
      this.searchType = SEARCH_TYPE_DEFALUT;
      this.search = null;
      this.startDate = null;
      this.endDate = null;
      if (this.pagination.page === 1) {
        this.getDataFromApi().then(data => {
          this.desserts = data.items;
          this.totalDesserts = data.total;
          this.loading = false;
        });
      } else {
        this.pagination.page = 1;
      }
    },
    //刷新概况数据
    refreshChartData() {
      let lineCahrt = this.$refs.lineChart;
      lineCahrt.showLoading({
        text: "加载中...",
        color: "#03a9f4",
        maskColor: "rgba(255, 255, 255, 0.4)"
      });
      this.getChartData()
        .then(res => {
          this.chartData = res;
          this.setChartOption();
          lineCahrt.hideLoading();
        })
        .catch(err => {
          console.error(err);
        });
    },
    //将chartData.store15Day 与 polar绑定
    setChartOption() {
      this.polar = {
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: ["消费总额", "卡主消费", "亲情消费", "共享消费"]
        },
        grid: {
          left: "2%",
          right: "2%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.chartData.store15Day.map(item => {
            return item.day_date;
          })
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "消费总额",
            data: this.chartData.store15Day.map(item => {
              return item.total;
            }),
            type: "line"
          },
          {
            name: "卡主消费",
            data: this.chartData.store15Day.map(item => {
              return item.owner;
            }),
            type: "line"
          },
          {
            name: "亲情消费",
            data: this.chartData.store15Day.map(item => {
              return item.family;
            }),
            type: "line"
          },
          {
            name: "共享消费",
            data: this.chartData.store15Day.map(item => {
              return item.share;
            }),
            type: "line"
          }
        ]
      };
    },
    switchover(){
      this.tableOrTimeline = !this.tableOrTimeline
    },
    jump () {
    console.log(document.body.scrollTop)
},
  },
  mounted() {
    let lineCahrt = this.$refs.lineChart;
    lineCahrt.showLoading({
      text: "加载中...",
      color: "#03a9f4",
      maskColor: "rgba(255, 255, 255, 0.4)"
    });
    this.getChartData()
      .then(res => {
        this.chartData = res;
        this.setChartOption();
        lineCahrt.hideLoading();
      })
      .catch(err => {
        lineCahrt.hideLoading();
      });
  }
};
</script>
<style scoped>
.echarts {
  width: 100% !important;
}
.backdrop {
  height: 600px;
  overflow:auto
}
</style>
